package com.pzhu.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pzhu.common.pojo.PageResult;
import com.pzhu.item.mapper.BrandMapper;
import com.pzhu.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired(required = false)
    private BrandMapper brandMapper;
    /**
     * 根据条件查询品牌信息排序分页
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();


        //根据name模糊查询，或者根据首字母查询
        if (StringUtils.isNotBlank(key)){
            //模糊查询
            criteria.andLike("name", "%"+"key"+"%").orEqualTo("letter",key);
        }
        //添加分页条件
        PageHelper.startPage(page,rows);
        //添加排序条件
        if (StringUtils.isNotBlank(sortBy)){
            //判断是否排序
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }

        List<Brand> brands = this.brandMapper.selectByExample(example);//.var快捷键
        //包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return  new PageResult<>(pageInfo.getTotal(),pageInfo.getList());

    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     */
    @Transactional//
    public void saveBrand(Brand brand,@RequestParam("cids") List<Long> cids) {
        //先新增Brand
//        Boolean flag = this.brandMapper.insertSelective(brand) == 1;
        this.brandMapper.insertSelective(brand);
        //insertSelective效率高于insert；


        //再新增中间表
//        if (flag){
            cids.forEach(cid -> {
                this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
                //通用mapper只能操作单张表，这里需要自定义sql语句
            });
//        }
    }


    public List<Brand> queryBrandByCid(Long cid) {
        return this.brandMapper.selectBrandByCid(cid);
    }
}
